import Layout from '@/views/pages/layout/index'
import {
  parseJSON
} from '@/components/storybook/utilties/tools'
import {
  meta
} from '@/components/storybook/settings/router'
import {
  isURL
} from '@/utils/validate'
import Vue from 'vue'
import {
  set,
  get
} from 'lodash'
import {
  constantRoutes
} from '@/components/storybook/router'

export function getMeta (route) {
  const {
    id,
    name,
    param,
    url
  } = route
  return Object.assign({}, meta, {
    menuId: id,
    title: name,
    param,
    iframeURL: isURL(url) && url
  })
}

export function getPath (route) {
  const name = route.name || ''
  return name.replace(/\s+/g, '')
}

export function getComponent (route) {
  let url = route.url || ''
  /**
   * /{{([^}}]+)?}}/g
   * {{ window.SITE_CONFIG["apiURL"] }}/aa =========> {{ window.SITE_CONFIG["apiURL"] }}
   */
  // eslint-disable-next-line no-eval
  url = url.replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2))
  if (!isURL(url)) {
    url = url.replace(/_/g, '-')
  }
  return () => import(`@/views/modules/${url}`)
}

export function getName (route) {
  let url = route.url || ''
  let param = route.param
  // eslint-disable-next-line no-eval
  url = url.replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2))
  if (isURL(url)) {
    return url.replace(/\//g, '-') + (param ? '$' + param.replace(/^\s*|\s*$/g, '') : '')
  }

  url = url.replace(/^\//, '').replace(/_/g, '-')

  return url.replace(/\//g, '-') + (param ? '$' + param.replace(/^\s*|\s*$/g, '') : '')
}

export function generateRoute (route, hasChildren = false) {
  const meta = getMeta(route)
  const name = getName(route)
  const rPath = getPath(route)
  const component = getComponent(route)
  const query = parseJSON(route.param)

  const path = !hasChildren ? `/${rPath}` : rPath

  let item = {
    name,
    path,
    meta,
    query,
    chidlren: []
  }

  if (hasChildren) {
    item.component = Layout
    return item
  }
  item.component = component

  return item
}

export function mapAsyncRoutes (routes) {
  return routes.reduce((result, route) => {
    if (route.name === 'Dashboards' || route.name === 'Datasets' || route.name === 'App' || route.name === 'Bots' || route.name === 'Widgets' || route.name === 'Form List') {
      route.children = []
    }
    const hasChildren = Array.isArray(route.children) && route.children.length

    const item = generateRoute(route, hasChildren)

    if (hasChildren) {
      const children = mapAsyncRoutes(route.children)
      return result.concat(children)
    }
    result.push(item)
    return result
  }, [])
}
export function getloginInfo () {
  Vue.prototype.$interface.other.getLoginConfigInfo({}).then(({data:res}) => {
    let tempHost = window.location.hostname
    if(tempHost && tempHost !== 'localhost' && res.data.length > 0) {         
      store.state.siteWebConfig = res.data.filter(e=>e.origin === tempHost)[0]          
    }
  })
}

export default {
  state: {
    routes: [],
    addRoutes: [],
    menus: window.SITE_CONFIG['menuList'] || [],
    dicts: window.SITE_CONFIG['dictList'] || [],
    buttons: window.SITE_CONFIG['permissions'] || [],
    user: null
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(state.addRoutes)
    },
    SET_MENUS (state, menus) {
      window.SITE_CONFIG['menuList'] = menus
      state.menus = menus
    },
    SET_DICTS (state, dicts) {
      window.SITE_CONFIG['dictList'] = dicts
      state.dicts = dicts
    },
    SET_BUTTONS (state, buttons) {
      window.SITE_CONFIG['permissions'] = buttons
      state.buttons = buttons
    },
    SET_USER (state, user) {
      state.user = user
    }
  },
  actions: {
    generateRoutes ({
      commit
    }) {
      return new Promise((resolve, reject) => {
        const params = {}
        if (sessionStorage.getItem('loginAsUserId')) {
          set(params, 'loginAsUserId', sessionStorage.getItem('loginAsUserId'))
        }
        if (sessionStorage.getItem('loginAsRoleId')) {
          set(params, 'loginAsRoleId', sessionStorage.getItem('loginAsRoleId'))
        }

        Vue.prototype.$interface.system.navMenuListApi(params).then(({
          data: response
        }) => {
          if (response.code !== 0) {
            return response.msg
          }
          const data = response.data || []
          let accessedRoutes = mapAsyncRoutes(data)

          commit('SET_ROUTES', accessedRoutes)
          commit('SET_MENUS', data)

          resolve(accessedRoutes)
        }).catch(error => {
          reject(error)
        })
      })
    },
    generateDicts ({
      commit
    }) {
      return new Promise((resolve, reject) => {
        Vue.prototype.$interface.system.generalListApi().then(({
          data: response
        }) => {
          if (response.code !== 0) {
            throw response.msg
          }
          const dicts = response.data || []
          commit('SET_DICTS', dicts)

          resolve(dicts)
        }).catch(error => {
          reject(error)
        })
      })
    },

    generateButtons ({
      commit
    }) {
      return new Promise((resolve, reject) => {
        const params = {}
        if (sessionStorage.getItem('loginAsUserId')) {
          set(params, 'loginAsUserId', sessionStorage.getItem('loginAsUserId'))
        }
        if (sessionStorage.getItem('loginAsRoleId')) {
          set(params, 'loginAsRoleId', sessionStorage.getItem('loginAsRoleId'))
        }
        Vue.prototype.$interface.system.getUserPermissionsApi(params).then(({
          data: response
        }) => {
          if (response.code !== 0) {
            throw response.msg
          }
          const buttons = response.data || []
          commit('SET_BUTTONS', buttons)

          resolve(buttons)
        }).catch(error => {
          reject(error)
        })
      })
    },
    generateUser ({
      commit
    }) {
      return new Promise((resolve, reject) => {
        Vue.prototype.$interface.login.loginUserInfoApi().then(({
          data: response
        }) => {
          if (response.code !== 0) {
            throw response.msg
          }
          const user = response.data || {}
          commit('SET_LOGIN_USER_INFO', user)
          commit('SET_USER', user)

          resolve(user)
        }).catch(error => {
          reject(error)
        })
      })
    },

    fillRouteMeta ({
    }, id) {
      return new Promise((resolve) => {
        Vue.prototype.$interface.system.getMenuInfoApi(id).then(({ data: response }) => {
          resolve(get(response, 'data.name'))
        })
      })
    }
  }
}
